import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
	strict: process.env.NODE_ENV === 'development',
	state: {
		list: [{
				id: 1,
				name: '高考',
				done: false
			},
			{
				id: 2,
				name: '作弊',
				done: false
			},
			{
				id: 3,
				name: '告白',
				done: true
			},
		],
		type: 'all',
	},
	mutations: {
		changeDone(state, id) {
			const todo = state.list.find((item) => item.id === id)
			todo.done = !todo.done
		},
		del(state, id) {
			state.list = state.list.filter((item) => item.id !== id)
		},
		add(state, name) {
			state.list.unshift({
				id: Date.now(),
				name,
				done: false,
			})
		},
		checkAll(state, value) {
			state.list.forEach((item) => (item.done = value))
		},
		changeType(state, type) {
			state.type = type
		},
		clear(state) {
			state.list = state.list.filter((item) => !item.done)
		},
	},
	actions: {
		clear(context) {
			setTimeout(() => {
				context.commit('clear')
			}, 1000)
		},
	},
	getters: {
		leftCount(state) {
			// list中没有完成的任务的个数
			return state.list.filter((item) => !item.done).length
		},
		isShowClear(state) {
			return state.list.some((item) => item.done)
		},
		showList(state) {
			if (state.type === 'active') {
				return state.list.filter((item) => !item.done)
			} else if (state.type === 'completed') {
				return state.list.filter((item) => item.done)
			} else {
				return state.list
			}
		},
	},
})

export default store
